package com.boot.until;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http请求类
 *
 */
@Slf4j
public class HttpUtil {

    //文件配置
    public static final String APP_KEY="e7e0886711004320";
    public static final String APP_SECRET="ZEpFti2Mzi6jZfI4GBkzxF9QnPTGpPlg";

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();

    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet (url);
        /*中文乱码*/
        httpget.setHeader(
                new BasicHeader ("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));

        //设置期望服务端返回的编码
        httpget.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送HttpPost请求，参数为map
     * @param url
     * @param map
     * @return
     */
    public static String sendPost(String url, Map<String, String> map) {
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair (entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity (formparams, Consts.UTF_8);
        HttpPost httppost = new HttpPost (url);
        httppost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity1 = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity1);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送不带参数的HttpPost请求
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        HttpPost httppost = new HttpPost (url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        try {
            result = EntityUtils.toString(entity);
        } catch (ParseException | IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 获取参数提示
     * @param params
     * @return
     */
    public static JsonArray getBaidu(String params){
        String test;
        test=sendGet ( "http://suggestion.baidu.com/su?wd="+params+"" );
        test=test.replaceAll ( "window.baidu.sug","" );
        test=test.substring ( test.indexOf ( "(" )+1,test.lastIndexOf ( ")" ) );
        JsonObject jsonObject=new JsonObject ();
        jsonObject=new JsonParser ().parse ( test ).getAsJsonObject ();
        JsonArray jsonArray=jsonObject.get ( "s" ).getAsJsonArray ();
        return jsonArray;
    }

    /**
     * 获取新闻的分类
     * @return
     */
    public static JsonObject getCategory(){
        JsonObject jsonObject=new JsonObject ();
        String result=sendGet ( "http://api.jisuapi.com/news/channel?appkey="+APP_KEY+"" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }

    /**
     * 获取类目下的新闻类别
     * @param channel
     * @param page
     * @param pagenum
     * @return
     */
    public static JsonObject getNewDetail(String channel,Integer page,Integer pagenum){
        JsonObject jsonObject=new JsonObject ();
        String result=sendGet ( "http://api.jisuapi.com/news/get?channel="+channel+"&start="+page+"&num="+pagenum+"&appkey="+APP_KEY+"" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }


    /**
     * 查找用户的天气
     * @param ip
     * @return
     */
    public static JsonObject getWeather(String ip){
        JsonObject jsonObject=new JsonObject ();
        String result=sendGet ( "http://route.showapi.com/9-4?showapi_appid=49813&ip="+ip+"&showapi_sign=0bfa98d246474468b67c7b3285342183" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }

    /**
     * 根据地区名更换区域天气
     * @param areaName
     * @return
     */
    public static JsonObject getWeatherByarea(String areaName){
        JsonObject jsonObject=new JsonObject ();
        log.info ( "地名={}",areaName );
        String result=sendGet ( "http://route.showapi.com/9-2?showapi_appid=49813&area="+areaName+"&showapi_sign=0bfa98d246474468b67c7b3285342183" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }

    /**
     * 根据ip分析城市
     * @param ip
     * @return
     */
    public static JsonObject getNameByIp(String ip){
        JsonObject jsonObject=new JsonObject ();
        String result=sendGet ( "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ip+"" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }

    /**
     * 图灵机器人的对话聊天
     * @param info
     * @return
     */
    public static JsonObject getRobot(String info){
        JsonObject jsonObject=new JsonObject ();
        String result=sendGet ( "http://www.tuling123.com/openapi/api?key=24561e519ea244faaa4f1816188cf4b3&userid=jun&info="+info+"" );
        jsonObject=new JsonParser ().parse ( result ).getAsJsonObject ();
        return jsonObject;
    }




    public static void main(String arg[]){
        /*String test=new String (  );
        test=sendGet ( "http://suggestion.baidu.com/su?wd=哈弗" );
        test=test.replaceAll ( "window.baidu.sug","" );
        test=test.substring ( test.indexOf ( "(" )+1,test.lastIndexOf ( ")" ) );
        JsonObject jsonObject=new JsonObject ();
        jsonObject=new JsonParser ().parse ( test ).getAsJsonObject ();
        JsonArray jsonArray=jsonObject.get ( "s" ).getAsJsonArray ();
        log.info ( "result={}",jsonArray );*/
       /* JsonObject jsonObject=getNameByIp ( "221.226.132.146" );
        log.info ( "ip={}",jsonObject );*/
       JsonObject jsonObject=getRobot ( "测试" );
       log.info ( "json={}",jsonObject );

    }
}